/**
 * 
 */
package hu.gbalage.httpserver;

import java.net.URL;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;

import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
 * @author Grill Balazs (balage.g@gmail.com)
 *
 */
public class ContextHandlerRegistry {

	public ContextHandlerRegistry(HTTPServerRegistry servers){
		IExtensionRegistry registry = Platform.getExtensionRegistry();  
		IExtensionPoint point = registry.getExtensionPoint(Constants.EP_CONTEXTHANDLER);
		for (IExtension extension : point.getExtensions()){  
			for (IConfigurationElement element : extension.getConfigurationElements()){
				//add(new HTTPServerEntry(element));
				String serverid = element.getAttribute(Constants.EPA_CONTEXTHANDLER_SERVER);
				String context = element.getAttribute(Constants.EPA_CONTEXTHANDLER_CONTEXT);
				
				for(IConfigurationElement handlerelement : element.getChildren()){
					HttpServer server = servers.get(serverid);
					HttpHandler handler = null;
					if (handlerelement.getName().equals(Constants.EPC_CONTEXTHANDLER_HANDLER)){
						try {
							handler = (HttpHandler)handlerelement.createExecutableExtension(Constants.EPA_CONTEXTHANDLER_HANDLER);
						} catch (CoreException e) {
							handler = null;
							e.printStackTrace();
						}
					}
					if (handlerelement.getName().equals(Constants.EPC_CONTEXTHANDLER_FILE)){
						Bundle bundle = Platform.getBundle(extension.getNamespaceIdentifier());
						URL url = bundle.getResource(Constants.EPA_CONTEXTHANDLER_RESOURCE);
						handler = new HttpSingleFile(url);
					}
					if ((handler != null)&&(server != null)){
						server.createContext(context, handler);
					}
				}
			}
		}
	}
	
}
